package sk.fiit.icp.welcome.view;

import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.resource.ContextRelativeResource;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.value.ValueMap;

import sk.fiit.icp.components.SignInSession;
import sk.fiit.icp.data.UsersDao;

public class HeaderSignInPanel extends Panel {

	@SpringBean(name = "usersDao")
	public UsersDao usersDao;

	public HeaderSignInPanel(String id) {
		super( id );

		add( new SignInForm( "signInForm" ) );
	}

	class SignInForm extends Form<Void> {

		private static final String EMAIL = "email";
		private static final String PASSWORD = "password";

		private final ValueMap properties = new ValueMap();

		public SignInForm(final String id) {
			super( id );

			add( new TextField<String>( EMAIL, new PropertyModel<String>( properties, EMAIL ) ) );
			add( new PasswordTextField( PASSWORD, new PropertyModel<String>( properties, PASSWORD ) ) );
			SubmitLink submitLink = new SubmitLink( "signInLink" );
			submitLink.add( new Image( "signInImage", new ContextRelativeResource( "/images/Page/signInButton.png" ) ) );
			add( submitLink );
		}

		@Override
		public final void onSubmit() {

			SignInSession session = getMySession();

			// Sign the user in
			if ( session.signIn( getEmail(), getPassword() ) ) {
				if ( !continueToOriginalDestination() ) {
					setResponsePage( getApplication().getHomePage() );
				}
			} else {

				String errmsg = getString( "feedback", null, "Unable to sign you in" );
				// Register the error message with the feedback panel
				error( errmsg );
			}
		}

		private String getPassword() {
			return properties.getString( PASSWORD );
		}

		private String getEmail() {
			return properties.getString( EMAIL );
		}

		private SignInSession getMySession() {
			return (SignInSession) getSession();
		}
	}

}
